package nku.csc660;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.HashMap;

public class SharedDataStructure {
	int numSocketsAllowed = 0;
	Boolean[] inUse;
	Socket[] sockets;
	BufferedReader[] bufferedReaders;
	PrintWriter[] printWriters;
	HashMap<Integer, String> clientNames = new HashMap<Integer, String>();

	public SharedDataStructure(int numSocketsAllowed)
	{
		this.numSocketsAllowed = numSocketsAllowed;
		sockets = new Socket[numSocketsAllowed];
		bufferedReaders = new BufferedReader[numSocketsAllowed];
		printWriters = new PrintWriter[numSocketsAllowed];
		inUse = new Boolean[numSocketsAllowed];
		for(int i = 0; i < numSocketsAllowed; i++){
			inUse[i] = false;
		}
	}

	public synchronized int isThereRoom()
	{
		for(int i = 0; i < numSocketsAllowed; i++){
			if(inUse[i] == false){
				inUse[i] = true;
				return i;
			}
		}
		return -1;
	}

	public synchronized void addToDataStructure(int id, Socket socket, PrintWriter pw, BufferedReader br)
	{
		sockets[id] = socket;
		printWriters[id] = pw;
		bufferedReaders[id] = br;
	}

	public synchronized void deleteFromDataStructure(int id) throws IOException{
		bufferedReaders[id].close();
		printWriters[id].close();
		sockets[id].close();
		inUse[id] = false;
	}

	public synchronized void sendBrodcastMessage(int sentId, String... lines){
		for(int i = 0; i < numSocketsAllowed; i++){
			if(inUse[i]){
				Server.sendMessage(printWriters[i], clientNames.get(sentId), lines);
			}
		}
	}

	public synchronized void sendToSpecificClient(int sentId, int id, String... lines){
		if(inUse[id]){
			Server.sendMessage(printWriters[id], clientNames.get(sentId), lines);
		}
	}

	public synchronized void sendToSpecificClientWho(int id){
		if(inUse[id]){
			String string = "";
			for(String temp: clientNames.values()){
				string += (temp + " ");
			}
			Server.sendMessage(printWriters[id], "SERVER", string);
		}
	}

	public synchronized void putName(int id, String name){
		clientNames.put(id, name);
	}
}
